package com.world.cat.app.utils;

import com.world.cat.app.AppConstant;
import com.world.cat.model.sys.Config;
import com.world.cat.service.sys.ConfigService;
import com.world.cat.service.sys.MenuService;
import com.world.cat.service.sys.RoleResourceService;
import com.world.common.generate.auto.QMapping;
import com.world.common.util.CollectionUtil;
import com.world.common.util.SysUtil;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by gang on 2016/10/19.
 */
public class AppUtils {
    //获取所有controller的class用于解析他们的注解，完成权限等的自动化配置
    public static List<Class> getAllControllerClass() {
        List<Class> controllerClasses = new ArrayList<>();
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        String classpath = AppUtils.class.getResource("/").toString();
        try {
            Resource[] resources = resourcePatternResolver.getResources(AppConstant.controller_pattern);
            for (int i = 0; i < resources.length; i++) {
                String source = resources[i].getURL().toString();
                String str = source.substring(classpath.length(), source.length() - 6).replace("/", ".");
                try {
                    controllerClasses.add(Class.forName(str));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return controllerClasses;
    }

    //一个controller底下有好多url这些url在展示的时候左侧的菜单需要点亮，
    // 1.首先看页面有没有QMapping(relatedUrl="")标识，如果有，就采用
    // 2.然后看页面本身是否是菜单，如果是关联菜单就是自己
    // 3.如果都不是，将当前Controller下的/home页面作为默认的关联菜单
    public static Map<String, String> getDefaultRelatedUrl() {
        Map<String, String> urlMap = new HashMap<>();
        List<Class> controllerClasses = getAllControllerClass();
        if (CollectionUtil.isNotEmpty(controllerClasses)) {
            for (Class controllerClass : controllerClasses) {
                RequestMapping annotation = (RequestMapping) controllerClass.getAnnotation(RequestMapping.class);
                if (annotation != null && ArrayUtils.isNotEmpty(annotation.value())) {
                    String baseUrl = annotation.value()[0];
                    Method[] methods = controllerClass.getDeclaredMethods();
                    if (ArrayUtils.isNotEmpty(methods)) {
                        for (Method method : methods) {
                            RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                            String fullUrl = "";
                            if (requestMapping != null && ArrayUtils.isNotEmpty(requestMapping.value())) {
                                fullUrl = baseUrl + requestMapping.value()[0];
                                //将权限的url与名字放到缓存里
                                if (ifControl(requestMapping.name())) {
                                    RoleResourceService.urlNameMap.put(fullUrl, requestMapping.name());
                                }
                            }
                            QMapping qMapping = method.getAnnotation(QMapping.class);
                            if (qMapping != null && SysUtil.isNotEmpty(qMapping.relatedUrl())) {
                                urlMap.put(fullUrl, qMapping.relatedUrl());
                            } else {
                                //如果url是菜单，那么应该点亮这个菜单
                                if (MenuService.urlMenuMap.containsKey(fullUrl)) {
                                    urlMap.put(fullUrl, fullUrl);
                                } else {
                                    urlMap.put(fullUrl, baseUrl + AppConstant.default_related_url_fix);
                                }
                            }
                        }
                    }
                }
            }
        }
        return urlMap;
    }

    //判断是否要管控这个资源(RequestMapping如果有name属性就表示需要加入控制，如果有name属性但是不想加入控制就在name属性值前面加个减号)
    //@RequestMapping(value = "/home") 不控制
    //@RequestMapping(value = "/home",name="列表") 控制
    //@RequestMapping(value = "/home",name="-列表") 不控制
    public static boolean ifControl(String name) {
        if (SysUtil.isNotEmpty(name) && !name.startsWith("-")) {
            return true;
        }
        return false;
    }

    public static String getConfigValue(String key) {
        Config config = ConfigService.configMap.get(key);
        if (config != null) {
            return config.getConfigValue();
        }
        return null;
    }
}
